package com.qianlou.springai01chat.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.openai.OpenAiAudioSpeechModel;
import org.springframework.ai.openai.OpenAiAudioSpeechOptions;
import org.springframework.ai.openai.api.OpenAiAudioApi;
import org.springframework.ai.openai.audio.speech.SpeechPrompt;
import org.springframework.ai.openai.audio.speech.SpeechResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.UUID;

@RestController
public class TextToSpeechController {


    @Resource
    private OpenAiAudioSpeechModel openAiAudioSpeechModel;

    /**
     * 参考文档
     * <a href="https://docs.spring.io/spring-ai/reference/api/audio/speech/openai-speech.html">参考文档</a>
     */
    @RequestMapping("/ai/text-to-speech")
    public void textToSpeech(HttpServletResponse servletResponse, @RequestParam("text") String text) throws IOException {
        OpenAiAudioSpeechOptions speechOptions = OpenAiAudioSpeechOptions.builder()
                .withModel("tts-1")
                .withVoice(OpenAiAudioApi.SpeechRequest.Voice.ALLOY)
                .withResponseFormat(OpenAiAudioApi.SpeechRequest.AudioResponseFormat.MP3)
                .withSpeed(1.0f)
                .build();
        SpeechPrompt speechPrompt = new SpeechPrompt(text, speechOptions);
        SpeechResponse response = openAiAudioSpeechModel.call(speechPrompt);
        byte[] buffer = response.getResult().getOutput();
        servletResponse.setHeader("content-disposition","attachment;fileName="
                + UUID.randomUUID().toString().replace("-", "") + ".mp3");
        ServletOutputStream outputStream = servletResponse.getOutputStream();
        outputStream.write(buffer);
        outputStream.flush();
        outputStream.close();
    }


}
